package com.sunshine.wrongquestionset.activity.add_question

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.google.android.material.dialog.MaterialAlertDialogBuilder

import com.google.android.material.snackbar.Snackbar

import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.activity.base.BaseActivity
import com.sunshine.wrongquestionset.utils.FileUtils.uriToFile
import com.sunshine.wrongquestionset.utils.TagUtils
import com.wanglu.photoviewerlibrary.PhotoViewer

import com.zzhoujay.richtext.ImageHolder
import com.zzhoujay.richtext.RichText
import com.zzhoujay.richtext.RichType
import com.zzhoujay.richtext.callback.OnImageClickListener

import kotlinx.android.synthetic.main.activity_add_question_expend.*

import java.util.*

/**
 * 在扩展模式下添加题目
 * 即类富文本编辑
 */
class AddQuestionExpendActivity : BaseActivity() {

    //当前编辑的文本是题干还是答案
    private var type = AddQuestionActivity.TYPE_TITLE
    private var text: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_question_expend)
        setTitle(getString(R.string.label_add_question_expend))

        type = intent.getIntExtra("type", AddQuestionActivity.TYPE_TITLE)
        text = intent.getStringExtra("text")?:""

        initEdit()
        updateMarkDown()
    }

    /**
     * 初始化编辑器
     */
    private fun initEdit() {
        edit_markdown.setText(text)
        //文字变化监听，用于实时更新预览面板
        edit_markdown.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                text = s.toString()
                updateMarkDown()
            }

        })
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_add_question_expend, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                val intent = Intent()
                intent.putExtra("text", text)
                setResult(type, intent)
                finish()
                return false
            }
            R.id.add_image -> {
                val intent = Intent(Intent.ACTION_GET_CONTENT)
                intent.type = "image/*"
                intent.addCategory(Intent.CATEGORY_OPENABLE)
                startActivityForResult(intent, TagUtils.ADD_QUESTION_EXPEND)
            }
            //预览模式不显示编辑界面
            R.id.show_model -> {
                guideline.setGuidelinePercent(1.0f)
                scrollView_show.visibility = View.VISIBLE
                textInputLayout_markdown.visibility = View.GONE
            }
            R.id.show_edit_model -> {
                guideline.setGuidelinePercent(0.5f)
                scrollView_show.visibility = View.VISIBLE
                textInputLayout_markdown.visibility = View.VISIBLE
            }
            R.id.edit_model -> {
                guideline.setGuidelinePercent(0.0f)
                scrollView_show.visibility = View.GONE
                textInputLayout_markdown.visibility = View.VISIBLE
            }
            R.id.delete_all -> {
                val builder = MaterialAlertDialogBuilder(this)
                builder.apply {
                    setTitle("警告")
                    setMessage(getString(R.string.delete_all_markdown_warning))
                    setCancelable(false)
                }
                builder.setNegativeButton("确定") {_, _ ->
                    text = ""
                    updateMarkDown()
                }
                builder.setPositiveButton("取消") {_, _ ->}
                builder.create().show()
            }
            R.id.get_help -> {
                val builder = MaterialAlertDialogBuilder(this)
                builder.apply {
                    setTitle(getString(R.string.warning_title))
                    setMessage(getString(R.string.markdown_help))
                    builder.setPositiveButton("确定") {_, _ ->}
                }
                builder.create().show()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onBackPressed() {
        val intent = Intent()
        intent.putExtra("text", text)
        setResult(type, intent)
        super.onBackPressed()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == TagUtils.ADD_QUESTION_EXPEND) {
            if (resultCode == Activity.RESULT_OK) {
                val uri = data!!.data // 获取图片的uri
                if (uri == null) {
                    Snackbar.make(add_question_expend_root, getString(R.string.load_image_fail), Snackbar.LENGTH_SHORT).show()
                } else {
                    val path = uri.uriToFile(this)?.absolutePath
                    if (path == null) {
                        Snackbar.make(add_question_expend_root, getString(R.string.load_image_fail), Snackbar.LENGTH_SHORT).show()
                    } else {
                        text += "\n ![${Date().time}]($path)\n"
                        edit_markdown.setText(text)
                        updateMarkDown()
                    }
                }
            }
        }
    }

    //刷新markdown显示内容
    private fun updateMarkDown(){
        RichText
            .from(text.replace("\n", "\n\n"))
            .type(RichType.markdown)
            .scaleType(ImageHolder.ScaleType.fit_auto)
            .imageClick(object : OnImageClickListener {
                override fun imageClicked(imageUrls: MutableList<String>?, position: Int) {
                    if (imageUrls.isNullOrEmpty()) return
                    PhotoViewer
                        .setClickSingleImg(imageUrls[position], ImageView(this@AddQuestionExpendActivity))   //因为本框架不参与加载图片，所以还是要写回调方法
                        .setShowImageViewInterface(object : PhotoViewer.ShowImageViewInterface {
                            override fun show(iv: ImageView, url: String) {
                                Glide.with(iv.context).load(url).into(iv)
                            }
                        })
                        .start(this@AddQuestionExpendActivity)
                }
            })
            .into(textView_markdown)
//        textView_markdown.post {
//            Thread {
//                //markdown中双\n换行
//                val spanned = MarkDown.fromMarkdown(text.replace("\n", "\n\n"), { source ->
//                    try {
//                        //主线程执行，效果不是很好
//                        val drawable = Drawable.createFromPath(source)
//                        drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
//                        drawable
//                    }catch (e: Exception) {
//                        Snackbar.make(add_question_expend_root, getString(R.string.load_image_fail_2), Snackbar.LENGTH_SHORT).show()
//                        null
//                    }
//                }, textView_markdown)
//                textView_markdown.post {
//                    textView_markdown.text = spanned
//                }
//            }.start()
//
//        }
    }
}